import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  // 捕获重复跳转同一个路由所引发的异常
  return originalPush.call(this, location).catch(err => { })
};
Vue.use(VueRouter)

const routes = [
  // 重定向
  { path: '/', redirect: '/home' },
  {
    path: '/home',
    name: 'home',
    component: HomeView,
    meta: {
      activeNum: 0,
      isShowTabbar: true
    },
    children: [
      {
        path: 'searchPopup',
        name: 'searchPopup',
        component: () => import('../views/SearchPopup.vue')
      }
    ]
  },
  {
    path: '/topic',
    name: 'Topic',
    meta: {
      activeNum: 1,
      isShowTabbar: true
    },
    component: () => import(/* webpackChunkName: "Topic" */ '../views/Topic.vue'),
  },
  {
    path: '/category',
    name: 'Category',
    meta: {
      activeNum: 2,
      isShowTabbar: true
    },
    component: () => import(/* webpackChunkName: "Category" */ '../views/Category.vue'),
  },
  {
    path: '/cart',
    name: 'Cart',
    meta: {
      activeNum: 3,
      isShowTabbar: true
    },
    component: () => import(/* webpackChunkName: "Cart" */ '../views/Cart.vue'),
  },
  {
    path: '/user',
    name: 'User',
    meta: {
      activeNum: 4,
      isShowTabbar: true
    },
    component: () => import(/* webpackChunkName: "User" */ '../views/User.vue'),
  },
  {
    path: '/productDetail',
    name: 'productDetail',
    component: () => import('../views/ProductDetail'),

  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})


// 路由拦截
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (to.path == '/cart') {// 判断去往购物车页面
    if (token) {
      next()
    } else {
      Vue.prototype.$toast('请先登录')
      setTimeout(() => {
        next("/user")
      }, 1000);
    }
  }

  next()
})

export default router
